package cn.enjoyedu.ch01.bio.me;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import static cn.enjoyedu.ch01.Ch01Const.DEFAULT_PORT;
import static cn.enjoyedu.ch01.Ch01Const.DEFAULT_SERVER_IP;

public class BioClient {

    public static void main(String[] args) throws IOException {


        Socket socket =  new Socket(DEFAULT_SERVER_IP,DEFAULT_PORT);

        System.out.println("请输入请求消息：");

        new ReadMsg(socket).start();

        PrintWriter pw = null;
        while(true){
            pw = new PrintWriter(socket.getOutputStream());
            pw.println(new Scanner(System.in).next());

            pw.flush();
        }

    }

    private static class ReadMsg extends Thread {
        Socket socket;
        public ReadMsg(Socket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())
            )) {
                String line = null;
                while (true) {
                    while ((line = br.readLine()) != null) {
                        System.out.printf("%s\n",line);
                    }
                }
            } catch (IOException e) {
               clear();
            }
        }

        private void clear() {
            if (socket == null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
